Spiral Matrix I
Question
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
|
|
You should return [1,2,3,6,9,8,7,4,5].
Analysis
利用四个变量colbegin,colend,rowbegin,rowend来记录遍历的每天边上次走到的位置,在遍历完某行某列之后,向内(加1减1操作)移动该边。
- 两个end的标记为长度-1,否则会导致数组的越界
- 在从下往上遍历的时候需要检查之前的操作后边界是否有重合,假如有重合的话跳过
Code
|
|
Spiral Matrix II
Question
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
|
|
Analysis
思路同上,反过来对数组进行填充
Code
|
|